package com.ctgu.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author ALEX
 * @since 2022/9/11 16:52
 */
public class SqlSessionUtils {
    public static <T> T getSqlSession(Class<T> type){
        T mapper = null;
        try {
            // 读取MyBatis的核心配置文件
            InputStream stream = Resources.getResourceAsStream("mybatis-config.xml");
            // 创建SqlSessionFactoryBuilder对象
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            // 通过核心配置文件所对应的字节输入流创建工厂类SqlSessionFactory，生产SqlSession对象
            SqlSessionFactory build = sqlSessionFactoryBuilder.build(stream);
            // 创建SqlSession对象，参数为true时sql自动提交，空参时需要手动提交或回滚
            SqlSession sqlSession = build.openSession(true);
            mapper = sqlSession.getMapper(type);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return mapper;
    }
}